package com.edu.app.controller.ai;

import com.edu.app.bean.core.SysCustomer;
import com.edu.app.bean.core.SysUser;
import com.edu.app.bean.virtualbean.KeyValueItems;
import com.edu.app.bean.virtualbean.NameValueItems;
import com.edu.app.bean.virtualbean.UserActByDate;
import com.edu.app.bean.virtualbean.customize.TeacherLessonRank;
import com.edu.app.constant.StaticConstant;
import com.edu.app.constant.SysMessage;
import com.edu.app.model.AIModel;
import com.edu.app.service.sys.ai.SysAIService;
import com.edu.app.service.sys.core.SysUserService;
import com.edu.app.util.ErrorUtil;
import com.edu.app.util.JWTUtil;
import com.edu.app.util.MsgUtil;

import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RequestMapping(value = "/api/ai")
@RestController
public class SysAIController {
    @Autowired
    SysAIService sysAIService;

    @Autowired
    SysUserService sysUserService;

    @GetMapping("/getNotActiveCustomers")
    @RequiresAuthentication
    public ModelMap getNotActiveCustomers(@RequestHeader("Authorization") String token, @RequestParam Integer range){
        try{
            String username = JWTUtil.getUsername(token);
            List<SysCustomer> sysCustomerList = sysAIService.getNotActiveCustomer(username, range);
            return MsgUtil.retMsg(SysMessage.GET_NOT_ACTIVE_CUSTOMER_SUCCEED, "customers", sysCustomerList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "/getTeacherPendingConfirmNum")
    @RequiresAuthentication
    public ModelMap getTeacherPendingConfirmNum(@RequestHeader("Authorization") String token){

        try{
            String username = JWTUtil.getUsername(token);
            Integer pendingNum = sysAIService.getTeacherPendingConfirmNum(username);
            return MsgUtil.retMsg(SysMessage.GET_PENDING_ACTIVITY_SUCCEED, StaticConstant.PENDING_ACTIVITY, pendingNum);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getTeacherPendingFeedbackNum")
    @RequiresAuthentication
    public ModelMap getTeacherPendingFeedbackNum(@RequestHeader("Authorization") String token){

        try{
            String username = JWTUtil.getUsername(token);
            Integer pendingNum = sysAIService.getTeacherPendingFeedbackNumber(username);
            return MsgUtil.retMsg(SysMessage.GET_PENDING_ACTIVITY_SUCCEED, StaticConstant.PENDING_ACTIVITY, pendingNum);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getTeacherLessonCompleteRank")
    @RequiresAuthentication
    public ModelMap getTeacherLessonCompleteRank(@RequestHeader("Authorization") String token){

        try{
            String username = JWTUtil.getUsername(token);
            NameValueItems nameValueItems = sysAIService.getTeacherLessonCompleteRank(username);
            return MsgUtil.retMsg(SysMessage.GET_TEACHER_LESSON_COMPLETE_RANK_SUCCEED, StaticConstant.TEACHER_RANK, nameValueItems);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getUserActListByDateWithRole")
    @RequiresAuthentication
    public ModelMap getUserActListByDateWithRole(@RequestHeader("Authorization") String token, @RequestParam("date") String date, @RequestParam("role") String role){

        try{
            String username = JWTUtil.getUsername(token);
            List<UserActByDate> userActByDateList = sysAIService.getUserActListByDateWithRole(date, role);
            return MsgUtil.retMsg(SysMessage.GET_USER_ACT_LIST_BY_DATE_SUCCEED, StaticConstant.USER_ACT_DATE_LIST, userActByDateList);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getUserActListByDateWithRoleAndUser")
    @RequiresAuthentication
    public ModelMap getUserActListByDateWithRoleAndUser(@RequestParam("date") String date, @RequestParam("role") String role, @RequestParam("username") String username, @RequestParam("actType") String actType){

        try{
            List<UserActByDate> userActByDateList = sysAIService.getUserActListByDateWithRoleAndUser(date, role, username, actType);
            return MsgUtil.retMsg(SysMessage.GET_USER_ACT_LIST_BY_DATE_SUCCEED, StaticConstant.USER_ACT_DATE_LIST, userActByDateList);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getAIModel")
    @RequiresAuthentication
    public ModelMap getAIModel(@RequestHeader("Authorization") String token){

        try{
            String username = JWTUtil.getUsername(token);
            AIModel aiModel = new AIModel(sysAIService.getNotActiveCustomer(username,7),
                    sysAIService.getTeacherPendingConfirmNum(username),
                    sysAIService.getTeacherPendingFeedbackNumber(username),
                    sysAIService.getTeacherLessonCompleteRank(username));
            return MsgUtil.retMsg(SysMessage.GET_TEACHER_LESSON_COMPLETE_RANK_SUCCEED, StaticConstant.AI_MODEL, aiModel);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "/getTeacherCompleteLessonNumber")
    @RequiresAuthentication
    public ModelMap getTeacherCompleteLessonNumber(@RequestParam Integer type, @RequestParam String date){

        try{
            List<NameValueItems> nameValueItemsList_1 = sysAIService.getTeacherCompleteLessonNumber(1, type, date);
            List<NameValueItems> nameValueItemsListDemo_1 = sysAIService.getTeacherDemoLessonNumber(1, type, date);

            List<NameValueItems> nameValueItemsList_2 = sysAIService.getTeacherCompleteLessonNumber(2, type, date);
            List<NameValueItems> nameValueItemsListDemo_2 = sysAIService.getTeacherDemoLessonNumber(2, type, date);

            List<NameValueItems> nameValueItemsList_3 = sysAIService.getTeacherCompleteLessonNumber(3, type, date);
            List<NameValueItems> nameValueItemsListDemo_3 = sysAIService.getTeacherDemoLessonNumber(3, type, date);

            List<TeacherLessonRank> teacherLessonRankList = new ArrayList<TeacherLessonRank>();

            for(NameValueItems nameValueItems1:nameValueItemsList_1){
                TeacherLessonRank teacherLessonRank = new TeacherLessonRank();
                teacherLessonRank.setId(nameValueItems1.getId());
                teacherLessonRank.setNickname(nameValueItems1.getName());
                teacherLessonRank.setOneOnOne(nameValueItems1.getValue());
                teacherLessonRank.setTotalLessons(teacherLessonRank.getOneOnOne());
                teacherLessonRank.setTotalPoints(teacherLessonRank.getOneOnOne());
                teacherLessonRankList.add(teacherLessonRank);
            }

            for(NameValueItems nameValueItems2: nameValueItemsList_2){
                Boolean hasItem = false;
                for(TeacherLessonRank teacherLessonRank: teacherLessonRankList){
                    if(teacherLessonRank.getId() == nameValueItems2.getId()){
                        teacherLessonRank.setOneOnTwo(nameValueItems2.getValue());
                        teacherLessonRank.setTotalLessons(teacherLessonRank.getTotalLessons() + teacherLessonRank.getOneOnTwo());
                        teacherLessonRank.setTotalPoints(teacherLessonRank.getTotalPoints() + teacherLessonRank.getOneOnTwo()*2);
                        hasItem = true;
                    }
                }

                if(!hasItem){
                    TeacherLessonRank teacherLessonRank = new TeacherLessonRank();
                    teacherLessonRank.setId(nameValueItems2.getId());
                    teacherLessonRank.setNickname(nameValueItems2.getName());
                    teacherLessonRank.setOneOnTwo(nameValueItems2.getValue());
                    teacherLessonRank.setTotalLessons(teacherLessonRank.getTotalLessons() + teacherLessonRank.getOneOnTwo());
                    teacherLessonRank.setTotalPoints(teacherLessonRank.getTotalPoints() + teacherLessonRank.getOneOnTwo()*2);
                    teacherLessonRankList.add(teacherLessonRank);
                }
            }

            for(NameValueItems nameValueItems3: nameValueItemsList_3){
                Boolean hasItem = false;
                for(TeacherLessonRank teacherLessonRank: teacherLessonRankList){
                    if(teacherLessonRank.getId() == nameValueItems3.getId()){
                        teacherLessonRank.setOneOnThree(nameValueItems3.getValue());
                        teacherLessonRank.setTotalLessons(teacherLessonRank.getTotalLessons() + teacherLessonRank.getOneOnThree());
                        teacherLessonRank.setTotalPoints(teacherLessonRank.getTotalPoints() + teacherLessonRank.getOneOnThree()*3);
                        hasItem = true;
                    }
                }

                if(!hasItem){
                    TeacherLessonRank teacherLessonRank = new TeacherLessonRank();
                    teacherLessonRank.setId(nameValueItems3.getId());
                    teacherLessonRank.setNickname(nameValueItems3.getName());
                    teacherLessonRank.setOneOnThree(nameValueItems3.getValue());
                    teacherLessonRank.setTotalLessons(teacherLessonRank.getTotalLessons() + teacherLessonRank.getOneOnThree());
                    teacherLessonRank.setTotalPoints(teacherLessonRank.getTotalPoints() + teacherLessonRank.getOneOnThree()*3);
                    teacherLessonRankList.add(teacherLessonRank);
                }
            }

            {
                Comparator<TeacherLessonRank> comparator = new Comparator<TeacherLessonRank>(){
                    public int compare(TeacherLessonRank s1, TeacherLessonRank s2) {
                        //先排总消课
                        if(s1.getTotalPoints()!=s2.getTotalPoints()){
                            return s2.getTotalPoints()-s1.getTotalPoints();
                        }
                        else{
                            //总消课相同，再看总课时
                            if(s1.getTotalLessons()!=s2.getTotalLessons()){
                                return s2.getTotalLessons()-s1.getTotalLessons();
                            }
                            else{
                                //最后以id来排序
                                return s2.getId()-s1.getId();
                            }
                        }
                    }
                };

                Collections.sort(teacherLessonRankList,comparator);
            }

            for(TeacherLessonRank teacherLessonRank: teacherLessonRankList){
                for(NameValueItems nameValueItems: nameValueItemsListDemo_1){
                    if(teacherLessonRank.getId() == nameValueItems.getId()){
                        teacherLessonRank.setDemoClass(nameValueItems.getValue());
                    }
                }

                for(NameValueItems nameValueItems: nameValueItemsListDemo_2){
                    if(teacherLessonRank.getId() == nameValueItems.getId()){
                        teacherLessonRank.setDemoClass(teacherLessonRank.getDemoClass() + nameValueItems.getValue());
                    }
                }
                for(NameValueItems nameValueItems: nameValueItemsListDemo_3){
                    if(teacherLessonRank.getId() == nameValueItems.getId()){
                        teacherLessonRank.setDemoClass(teacherLessonRank.getDemoClass() + nameValueItems.getValue());
                    }
                }
            }

            return MsgUtil.retMsg(SysMessage.GET_TEACHER_LESSON_COMPLETE_NUMBER_SUCCEED, "teacher_rank_list", teacherLessonRankList);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }

    }

    @GetMapping(value = "pages/getPoStudentStatusToday")
    @RequiresAuthentication
    public ModelMap getPoStudentStatusToday(@RequestParam Integer offset,
                                       @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoStudentStatus(offset, limit, 0);
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoStudentStatusFuture")
    @RequiresAuthentication
    public ModelMap getPoStudentStatusFuture(@RequestParam Integer offset,
                                       @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoStudentStatus(offset, limit, 1);
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoStudentStatusComplete")
    @RequiresAuthentication
    public ModelMap getPoStudentStatusComplete(@RequestParam Integer offset,
                                               @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoStudentStatus(offset, limit, 2);
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoStudentStatusAll")
    @RequiresAuthentication
    public ModelMap getPoStudentStatusAll(@RequestParam Integer offset,
                                               @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoStudentStatus(offset, limit, 3);
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoStudentStatusMine")
    @RequiresAuthentication
    public ModelMap getPoStudentStatusMine(@RequestHeader("Authorization") String token, @RequestParam Integer offset,
                                          @RequestParam Integer limit){
        try{
            String username = JWTUtil.getUsername(token);
            SysUser sysUser = sysUserService.getUserByName(username);
            PageInfo pageInfo = sysAIService.getPoStudentStatusMine(offset, limit, sysUser.getNickname());
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getMarketingStatusByMonth")
    @RequiresAuthentication
    public ModelMap getMarketingStatusByMonth(@RequestParam String dateYYMM){
        try{
            List<KeyValueItems> keyValueItemsList = sysAIService.getMarketingStatus(dateYYMM);
            return MsgUtil.retMsg(SysMessage.GET_PO_STUDENT_LIST_SUCCEED, "ai_status_month", keyValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getDemoClassStatusByMonth")
    @RequiresAuthentication
    public ModelMap getDemoClassStatusByMonth(@RequestParam String dateYYMM){
        try{
            List<KeyValueItems> keyValueItemsList = sysAIService.getDemoClassStatus(dateYYMM);
            return MsgUtil.retMsg(SysMessage.GET_DEMO_CLASS_LIST_SUCCEED, "ai_status_month", keyValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getClassCompleteStatus")
    @RequiresAuthentication
    public ModelMap getClassCompleteStatus(@RequestParam String dateYYMM){
        try{
            List<KeyValueItems> keyValueItemsList = sysAIService.getClassCompleteStatus(dateYYMM);
            return MsgUtil.retMsg(SysMessage.GET_COMPLETE_CLASS_LIST_SUCCEED, "ai_status_month", keyValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getMemberAgeRange")
    @RequiresAuthentication
    public ModelMap getMemberAgeRange(){
        try{
            List<KeyValueItems> keyValueItemsList = sysAIService.getMemberAgeRange();
            return MsgUtil.retMsg(SysMessage.GET_MEMBER_AGE_RANGE_SUCCEED, "ai_status_age", keyValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoCustomerCompleteDemoAll")
    @RequiresAuthentication
    public ModelMap getPoCustomerCompleteDemoAll(@RequestParam Integer offset,
                                          @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoCustomerStatus(offset, limit, 0);
            return MsgUtil.retMsg(SysMessage.GET_PO_CUSTOMER_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoCustomerStatusCompleteDemoClassAllNumber")
    @RequiresAuthentication
    public ModelMap getPoCustomerStatusCompleteDemoClassAllNumber(){
        try{
            Integer number = sysAIService.getPoCustomerStatusCompleteDemoClassAllNumber();
            return MsgUtil.retMsg(SysMessage.GET_COUNT_NUM_SUCCEED, "number", number);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "pages/getPoCustomerPendingDemoAll")
    @RequiresAuthentication
    public ModelMap getPoCustomerPendingDemoAll(@RequestParam Integer offset,
                                                 @RequestParam Integer limit){
        try{
            PageInfo pageInfo = sysAIService.getPoCustomerStatus(offset, limit, 1);
            return MsgUtil.retMsg(SysMessage.GET_PO_CUSTOMER_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getPoCustomerNumber")
    @RequiresAuthentication
    public ModelMap getPoCustomerNumber(){
        try{
            Integer completeNumber = sysAIService.getPoCustomerStatusCompleteDemoClassAllNumber();
            Integer pendingNumber = sysAIService.getPoCustomerStatusPendingDemoClassAllNumber();
            ModelMap map = MsgUtil.retMsg(SysMessage.GET_COUNT_NUM_SUCCEED, "completeNumber", completeNumber);
            map.put("pendingNumber", pendingNumber);

            return map;
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    //for sales
    @GetMapping(value = "pages/getPoCustomerMine")
    @RequiresAuthentication
    public ModelMap getPoCustomerMine(@RequestHeader("Authorization") String token,
                                      @RequestParam Integer offset,
                                      @RequestParam Integer limit,
                                      @RequestParam Integer type){
        try{
            String username = JWTUtil.getUsername(token);
            PageInfo pageInfo = sysAIService.getPoCustomerByUser(offset, limit, username,type);
            return MsgUtil.retMsg(SysMessage.GET_PO_CUSTOMER_LIST_SUCCEED, "page_info", pageInfo);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    /*New Rest APIs for sales and teachers*/
    @GetMapping(value = "getUserActivityRank")
    @RequiresAuthentication
    public ModelMap getUserActivityRank(@RequestParam Integer status, @RequestParam String type, @RequestParam String date){
        try{
            List<NameValueItems> totalNumberList = sysAIService.getUserActivityTotalNumber(status, type, date);
            List<NameValueItems> numberList = sysAIService.getUserActivityNumber(status, type, date);

            ModelMap map = MsgUtil.retMsg(SysMessage.GET_USER_ACTIVITY_TOTAL_NUMBER_SUCCEED, "totalNumberList", totalNumberList);
            map.put("numberList", numberList);
            return map;
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getUserActivityTotalNumber")
    @RequiresAuthentication
    public ModelMap getUserActivityTotalNumber(@RequestParam Integer status, @RequestParam String type, @RequestParam String date){
        try{
            List<NameValueItems> nameValueItemsList = sysAIService.getUserActivityTotalNumber(status, type, date);
            return MsgUtil.retMsg(SysMessage.GET_USER_ACTIVITY_TOTAL_NUMBER_SUCCEED, "user_act_total_num_list", nameValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "getUserActivityNumber")
    @RequiresAuthentication
    public ModelMap getUserActivityNumber(@RequestParam Integer status, @RequestParam String type, @RequestParam String date){
        try{
            List<NameValueItems> nameValueItemsList = sysAIService.getUserActivityNumber(status, type, date);

            return MsgUtil.retMsg(SysMessage.GET_USER_ACTIVITY_NUMBER_SUCCEED, "user_act_num_list", nameValueItemsList);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }
}
